package com.EAsystem.controller.admin;

import com.EAsystem.annotation.RequireRole;
import com.EAsystem.entity.User;
import com.EAsystem.service.UserService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
@RequireRole({1}) // 只有管理员可以访问
public class AdminManagementController {

    @Autowired
    private UserService userService;

    /**
     * 管理员信息管理页面
     */
    @GetMapping("/admin")
    public String adminPage(@RequestParam(defaultValue = "1") int page,
                           @RequestParam(defaultValue = "5") int size,
                           @RequestParam(required = false) String adminName,
                           Model model) {
        
        PageInfo<User> pageInfo;
        
        // 根据条件查询管理员（角色为1）
        if (adminName != null && !adminName.trim().isEmpty()) {
            User searchUser = new User();
            searchUser.setRealName(adminName.trim());
            searchUser.setRole(1); // 管理员角色
            pageInfo = userService.findByCondition(searchUser, page, size);
        } else {
            User searchUser = new User();
            searchUser.setRole(1); // 只查询管理员
            pageInfo = userService.findByCondition(searchUser, page, size);
        }
        

        List<Integer> pageNumbers = new ArrayList<>();
        for (int i = 1; i <= pageInfo.getPages(); i++) {
            pageNumbers.add(i);
        }
        
        model.addAttribute("admins", pageInfo.getList());
        model.addAttribute("currentPage", page);
        model.addAttribute("pageSize", size);
        model.addAttribute("totalPages", pageInfo.getPages());
        model.addAttribute("totalRecords", pageInfo.getTotal());
        model.addAttribute("searchAdminName", adminName);
        model.addAttribute("pageNumbers", pageNumbers);
        
        return "admin/admin";
    }

    /**
     * 查看管理员详情
     */
    @GetMapping("/admin/view/{id}")
    @ResponseBody
    public Map<String, Object> viewAdmin(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            User admin = userService.findById(id);
            if (admin != null && admin.getRole() == 1) {
                result.put("success", true);
                result.put("admin", admin);
            } else {
                result.put("success", false);
                result.put("message", "管理员记录不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取管理员信息失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 删除管理员记录
     */
    @GetMapping("/admin/delete/{id}")
    public String deleteAdmin(@PathVariable Integer id) {
        userService.delete(id);
        return "redirect:/admin/admin";
    }

    /**
     * 批量删除管理员记录
     */
    @GetMapping("/admin/batchDelete")
    public String batchDeleteAdmins(@RequestParam("ids") String ids) {
        if (ids != null && !ids.isEmpty()) {
            for (String id : ids.split(",")) {
                try {
                    userService.delete(Integer.valueOf(id));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/admin/admin";
    }

    /**
     * 新增管理员
     */
    @PostMapping("/admin/add")
    @ResponseBody
    public Map<String, Object> addAdmin(@RequestParam String username,
                                       @RequestParam String password,
                                       @RequestParam String realName,
                                       @RequestParam(required = false) String phone,
                                       @RequestParam(required = false) String email,
                                       @RequestParam(defaultValue = "1") Integer status) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            if (userService.findByUsername(username) != null) {
                result.put("success", false);
                result.put("message", "用户名已存在");
                return result;
            }
            
            User admin = new User();
            admin.setUsername(username);
            admin.setPassword(password);
            admin.setRealName(realName);
            admin.setRole(1); // 管理员角色
            admin.setStatus(status);
            
            boolean success = userService.add(admin);
            if (success) {
                result.put("success", true);
                result.put("message", "新增管理员成功");
            } else {
                result.put("success", false);
                result.put("message", "新增管理员失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "新增管理员失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑管理员
     */
    @PostMapping("/admin/edit")
    @ResponseBody
    public Map<String, Object> editAdmin(@RequestParam Integer id,
                                        @RequestParam String username,
                                        @RequestParam(required = false) String password,
                                        @RequestParam String realName,
                                        @RequestParam(required = false) String phone,
                                        @RequestParam(required = false) String email,
                                        @RequestParam(defaultValue = "1") Integer status) {
        Map<String, Object> result = new HashMap<>();
        try {
            User admin = userService.findById(id);
            if (admin == null || admin.getRole() != 1) {
                result.put("success", false);
                result.put("message", "管理员记录不存在");
                return result;
            }
            
            // 检查用户名是否被其他用户使用
            User existingUser = userService.findByUsername(username);
            if (existingUser != null && !existingUser.getId().equals(id)) {
                result.put("success", false);
                result.put("message", "用户名已被其他用户使用");
                return result;
            }
            
            admin.setUsername(username);
            if (password != null && !password.trim().isEmpty()) {
                admin.setPassword(password);
            }
            admin.setRealName(realName);
            admin.setStatus(status);
            
            boolean success = userService.update(admin);
            if (success) {
                result.put("success", true);
                result.put("message", "编辑管理员成功");
            } else {
                result.put("success", false);
                result.put("message", "编辑管理员失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "编辑管理员失败：" + e.getMessage());
        }
        return result;
    }
} 